//
//  ChoosePhotoAlbum.m
//  Gone
//
//  Created by xiaowuxiaowu on 15/7/2.
//  Copyright (c) 2015年 xiaowuxiaowu. All rights reserved.
//

#import "ChoosePhotoAlbum.h"

#import <AssetsLibrary/AssetsLibrary.h>
#import <AVFoundation/AVFoundation.h>
#import <Photos/Photos.h>

@interface ChoosePhotoAlbum()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (nonatomic,weak)UIImagePickerController *picker;
@end

@implementation ChoosePhotoAlbum

+(ChoosePhotoAlbum *)shareSingeWithViewController:(UIViewController *)viewController {

     ChoosePhotoAlbum *album= [[ChoosePhotoAlbum alloc]init];
        album.ViewController = viewController;
        album.maximumNumberOfSelection = 9;
        album.videoMaximumDuration = 5.0f;

    return album;

}


//从相册选择
-(void)localPhoto:(ChoosePhotoAlbumBlock)block{
    
    if(![self isOpen]){
        return;
    }
    
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    //资源类型为图片库
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    picker.allowsEditing = self.isEditedImage;
    [self.ViewController presentViewController:picker animated:YES completion:nil];
    self.block = block;
    _picker = picker;
}



//拍照
-(void)takePhoto:(ChoosePhotoAlbumBlock)block{
    
    if(![self isOpen]){
        
        return;
    }
    
     self.block = block;
    
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = self.isEditedImage;
        //资源类型为照相机
        picker.sourceType = sourceType;
        [self.ViewController presentViewController:picker animated:YES completion:nil];
         _picker = picker;
        
    }else {
        //DLog(@"该设备无摄像头");
    }
}
//录制视频
-(void)takeVideoCamera:(BOOL)isCamera block:(ChooseVideoAlbumBlock)block{
    
    
    if(![self isOpen]){
        
        return;
    }
    
    self.videoBlock = block;
    
    //资源类型为照相机
    UIImagePickerControllerSourceType sourceType = isCamera ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
    //判断是否有相机
    if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;//;self.isEditedImage;
        //资源类型为照相机
        picker.sourceType = sourceType;
     
        //picker.mediaTypes =
      //  [NSArray arrayWithObject:(NSString *)kUTTypeMovie];
        // 确定摄像，非照像。
          NSArray* availableMedia = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
        picker.mediaTypes =  !isCamera ? [NSArray arrayWithObject:(NSString *)kUTTypeMovie] :[NSArray arrayWithObject:availableMedia[1]];
           picker.videoMaximumDuration = round(self.videoMaximumDuration);
           picker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
           picker.modalPresentationStyle = UIModalPresentationPopover;
        
        [self.ViewController presentViewController:picker animated:YES completion:NULL];
         _picker = picker;
        
    }else {
    }

}

#pragma 用户选择好图片后的回调函数



-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    
    if (picker.sourceType==UIImagePickerControllerSourceTypeCamera) {
        //保存图片到相册
        UIImage *tempSaveImage= self.isEditedImage ? [info objectForKey:@"UIImagePickerControllerEditedImage"] : info[@"UIImagePickerControllerOriginalImage"];
       
        if(!tempSaveImage){
            
             UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([(NSURL *)[info objectForKey:UIImagePickerControllerMediaURL] absoluteString]);
            
        }else{
            
            UIImageWriteToSavedPhotosAlbum(tempSaveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
            
        }
    }
    
    UIImage *tempSaveImage= self.isEditedImage ? [info objectForKey:@"UIImagePickerControllerEditedImage"] : info[@"UIImagePickerControllerOriginalImage"];
   
    
    if (tempSaveImage != nil) {
        
//        if(picker.sourceType==UIImagePickerControllerSourceTypeCamera){
//            return;
//        }
        
        if (tempSaveImage.size.width > 1023) {
            
            NSData *imageData=UIImageJPEGRepresentation(tempSaveImage, 0.9);
            tempSaveImage=[UIImage imageWithData:imageData];
            
        }
        
        
        if(IOS8){

            
            id x = info[UIImagePickerControllerMediaURL];
            PHAsset *asset;
            if(x){
                PHFetchResult *fetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[x] options:nil];
                asset = fetchResult.firstObject;
            }
             self.block(tempSaveImage,asset,picker,info);
            
        }else{
            
            ALAssetsLibrary   *lib = [[ALAssetsLibrary alloc] init];
            [lib assetForURL:[NSURL URLWithString:info[UIImagePickerControllerReferenceURL]] resultBlock:^(ALAsset *asset)
             {
                 //在这里使用asset来获取图片
                 self.block(tempSaveImage,asset,picker,info);
             }failureBlock:^(NSError *error){
                 }
             ];
        }
        
        [picker dismissViewControllerAnimated:YES completion:nil];
       
      
    }else{
        
       
        if (!info)
            return ;
        //        NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
        
         self.videoBlock(nil,nil,info,NO,picker);
        return;
        
       
        
    }
 
    

}

+(void)saveInfo:(NSDictionary *)info export:(NSString *)exportPath chooseVideoAlbumBlock:(ChooseVideoAlbumBlock)block{
    
    
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:info[@"UIImagePickerControllerMediaURL"] options:nil];
    //   NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];
    AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset presetName:AVAssetExportPresetPassthrough];
//    NSString *exportPath = [NSString stringWithFormat:@"%@/%@.mp4",
//                            [NSHomeDirectory() stringByAppendingString:@"/tmp"],
//                            @"4"];
//    NSFileManager *fileManage = [NSFileManager defaultManager];
//    NSError *error;
//    if(![fileManage removeItemAtPath:exportPath error:&error]){
//        NSLog(@"Unable to move file: %@", [error localizedDescription]);
//    }
    exportSession.outputURL = [NSURL fileURLWithPath:exportPath];
    NSLog(@"%@", exportPath);
    exportSession.outputFileType = AVFileTypeMPEG4;
    [exportSession exportAsynchronouslyWithCompletionHandler:^{
        
        switch ([exportSession status]) {
            case AVAssetExportSessionStatusFailed:{
                block(nil,exportPath,info,YES,nil);
                 NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
                dispatch_async(dispatch_get_main_queue(), ^{
                    [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
                        ;
                    } title:@"提示" message:@"拍摄视频出错" cancelButtonName:@"确定" otherButtonTitles:nil, nil];
                });
            }
                break;
            case AVAssetExportSessionStatusCancelled:
                NSLog(@"Export canceled");
                break;
            case AVAssetExportSessionStatusCompleted:{
                block([XWCommon xw_getVideoImage:exportPath],exportPath,info,NO,nil);
            }
                NSLog(@"转换成功");
                break;
            default:
                break;
        }
    }];
    
}

//保存图片到相册的回调函数
-(void) image: (UIImage *)image didFinishSavingWithError: (NSError *)error
  contextInfo: (void *) contextInfo{
    
    NSString *msg=nil;
    if (error==NULL) {
        msg=@"保存图片成功";
    }else {
        msg=@"保存图片失败";
    }
    PHFetchOptions*options = [[PHFetchOptions alloc]init];
    
    options.sortDescriptors=@[[NSSortDescriptor sortDescriptorWithKey:@"creationDate"ascending:NO]];
    
    PHFetchResult*assetsFetchResults = [PHAsset fetchAssetsWithOptions:options];
   self.block(image,assetsFetchResults.firstObject,_picker,nil);
    DLog(@"msg=%@",msg);
}

-(void)imagePickerControllerDidCancel{
    
    [self imagePickerControllerDidCancel:_picker];
    
}

#pragma 编辑图片的取消回调函数
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

-(BOOL )isOpen{
   
    if([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo] == AVAuthorizationStatusDenied){
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"打开相机失败"
                                                       message:@"请打开 设置-隐私-相机 来进行设置"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else if ([ALAssetsLibrary authorizationStatus] == ALAuthorizationStatusDenied) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"读取相册失败"
                                                       message:@"请打开 设置-隐私-照片 来进行设置"
                                                      delegate:nil
                                             cancelButtonTitle:@"确定"
                                             otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }
    
    return YES;
    
}

-(void)morePhoto{
    
//    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:self.maximumNumberOfSelection delegate:self];
//
//    imagePickerVc.allowPickingVideo = NO;
//    // You can get the photos by block, the same as by delegate.
//    // 你可以通过block或者代理，来得到用户选择的照片.
//   // [imagePickerVc setDidFinishPickingPhotosHandle:self.didFinishPickingPhotosHandle];
////    typeof(imagePickerVc) __weak vc = imagePickerVc;
////    [imagePickerVc setImagePickerControllerDidCancelHandle:^{
////        [vc dismissViewControllerAnimated:YES completion:nil];
////    }];
//    [self.ViewController presentViewController:imagePickerVc animated:YES completion:nil];
}
//-(void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
//    DLog(@"----%@",photos);
//    self.didFinishPickingPhotosHandle(photos,assets,isSelectOriginalPhoto);
//}


@end
